package com.sudong;

import com.sudong.dao.UserMapper;
import com.sudong.pojo.User;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;
import java.util.Set;

public class MyReaml extends AuthorizingRealm {
    @Resource
    UserMapper userMapper;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        String userid = (String) principalCollection.getPrimaryPrincipal();
        Set roles = userMapper.findUserRolesById(userid);
        Set perms = userMapper.findUserPermsById(userid);

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(roles);
        authorizationInfo.setStringPermissions(perms);

        return authorizationInfo;
    }
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String userid = (String) authenticationToken.getPrincipal();
        User user =userMapper.findUserById(userid);
        SimpleAuthenticationInfo simpleAuthenticationInfo=null;
        if(user!=null){
            simpleAuthenticationInfo = new SimpleAuthenticationInfo(user.getId(),user.getPassword(), ByteSource.Util.bytes(user.getSalt()),this.getName());
        }
        return simpleAuthenticationInfo;
    }
}
